package com.dragon.codefx;

import com.dragon.codefx.config.JavaFXConfig;
import javafx.application.Application;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.dragon")  // 扫描组件
public class CodeFxApplication extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    private ConfigurableApplicationContext context;

    @Override
    public void init() {
        // 创建数据库目录（如果不存在）
        createDatabaseDirectoryIfNotExists();
        
        // 启动Spring容器
        this.context = new SpringApplicationBuilder(CodeFxApplication.class)
                .headless(false) // 重要：禁用headless模式
                .run();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // 从 Spring容器获取JavaFX配置类并启动JavaFX应用
        JavaFXConfig javaFXConfig = context.getBean(JavaFXConfig.class);
        javaFXConfig.start(primaryStage);
    }
        
    @Override
    public void stop() throws Exception {
        // 关闭Spring容器
        if (context != null) {
            context.close();
        }
    }
        
    /**
     * 创建数据库目录
     */
    private void createDatabaseDirectoryIfNotExists() {
        try {
            String userDir = System.getProperty("user.dir");
            java.nio.file.Path dbPath = java.nio.file.Paths.get(userDir, "db");
            if (!java.nio.file.Files.exists(dbPath)) {
                java.nio.file.Files.createDirectories(dbPath);
                System.out.println("数据库目录已创建: " + dbPath.toString());
            }
        } catch (Exception e) {
            System.err.println("创建数据库目录失败: " + e.getMessage());
        }
    }
}
